package base.tools;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;

import base.tools.Scan;

public class Tools {
  public static final String SPAN_START = "<span style=color:red>";
  public static final String SPAN_END = "</span>";
  public static final String B_START = "<b>";
  public static final String B_END = "</b>";
  private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

  public static String replace(String oldstr, String str1, String str2) {
    String tmpstr = oldstr;
    if (tmpstr != null) {
      tmpstr = tmpstr.replaceAll(str1, str2);
    }
    return tmpstr;
  }

  public static String[] split(String strT, String strB) {
    Vector vct = new Vector();
    if (strT == null || strT.trim().length() == 0)
      return null;

    int intStart = 0, intEnd = 0;
    while (strT.indexOf(strB, intStart) > -1) {
      intEnd = strT.indexOf(strB, intStart);
      vct.add(strT.substring(intStart, intEnd));
      intStart = ++intEnd;
    }
    vct.add(strT.substring(intEnd));
    return (String[]) vct.toArray(new String[vct.size()]);
  }

  
  public static String cutStringBoldfaced(String scr, int length, String tail) {
    boolean fSpan = false,
        fB = false;
    if (scr != null) {
      if (scr.indexOf(SPAN_END) != -1) {
        fSpan = true;
        scr = scr.replaceAll(SPAN_END, "").replaceAll(SPAN_START, "");
      }
      if (scr.indexOf(B_END) != -1) {
        fB = true;
        scr = scr.replaceAll(B_END, "").replaceAll(B_START, "");
      }

      if (scr.length() > length) {
        scr = scr.substring(0, length);
      }
      if (tail != null && tail.length() > 0) {
        if (tail.equals("..."))
          scr = scr.substring(0, scr.length() - 2) + "...";
        else
          scr = scr + tail;
      }

      if (fSpan)
        scr = SPAN_START + scr + SPAN_END;
      if (fB)
        scr = B_START + scr + B_END;
      return scr;
    }
    else {
      return "";
    }
  }

  public static String cutDecimal(String scr, int length) {
    String aim = scr;

    if (scr != null) {
      if (scr.indexOf('.') > 0) {
        if (length == 0) {
          aim = scr.substring(0, scr.indexOf('.'));
        }
        else {
          String zheng = scr.substring(0, scr.indexOf('.'));
          String xiao = scr.substring(scr.indexOf('.'), scr.length());
          if (xiao.length() > length) {
            xiao = xiao.substring(0, length + 1);
          }
          aim = zheng + xiao;
        }
      }

    }

    return aim;
  }

  public static String replaceAnd(String oldStr, String oldSeparate,
                                  String newSeparate) {
    String ret = "";
    if (oldStr != null) {

      ret = oldStr;

      ret = ret.replaceAll(oldSeparate, newSeparate);

      if (ret.startsWith(newSeparate))
        ret = ret.substring(newSeparate.length());
      if (ret.endsWith(newSeparate))
        ret = ret.substring(0, ret.length() - newSeparate.length());

    }
    return ret;
  }

  public static String replaceAnd(String oldStr) {
    String ret = "";

    String temp[] = null;

    if (oldStr != null) {

      temp = oldStr.split("&");

      for (int i = 0; i < temp.length; i++) {
        ret += temp[i];
      }

    }
    return ret;
  }

 
  public static String generatePasswd(int passwdLen) {
    String passwd = "";

    String[] passChar = {
        "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};

    Random r = new Random(System.currentTimeMillis());

    for (int i = 0; i < passwdLen; i++) {
      passwd += passChar[r.nextInt(10)];
    }

    return passwd;

  }

  

  public static boolean getifzhw() {
    Properties prop = System.getProperties();
    Enumeration item = prop.keys();
    if (prop.getProperty("file.encoding").toUpperCase().equals("GBK") ||
        prop.getProperty("file.encoding").toUpperCase().equals("GB2312"))
      return true;
    else
      return false;
  }


  public static String StrToHtml(String oldString) {
    if (oldString != null) {
//        String newString = "";
      String str1 = "";
      oldString = oldString.replaceAll(String.valueOf(' '), "&nbsp;").
          replaceAll(String.valueOf('\n'), "<br>");
      oldString = oldString.replaceAll(String.valueOf('\r'), "");
      return oldString;
    }
    return "";
  }

  public static String purgeSpecialNotation(String origin)
  {
    if (origin != null)
      return origin.replaceAll(String.valueOf(' '),"")
          .replaceAll(String.valueOf('\n'),"")
          .replaceAll(String.valueOf('\r'),"")
          .replaceAll("<br>","").replaceAll("<br />","")
          .replaceAll("&nbsp;","")
          .replaceAll("\"","")
          .replaceAll("\'","");
    else
      return "";
  }

  public static String HtmlToStr(String html)
  {
    if (html != null) {
      String str1 = "";
      html = html.replaceAll("&nbsp;",String.valueOf(' ')).replaceAll("<br>",String.valueOf('\n'));
      return html;
    }
    return "";
  }

  public static String toByteName(String inStr) throws Exception {
    byte[] b = inStr.getBytes("GBK");
    String outStr = "";
    char tmpchar = ' ';

    for (int i = 0; i < b.length; i++) {
      if (b[i] < 0) {
        outStr = outStr + "%" + Integer.toHexString(256 + b[i]);
      }
      else {
        tmpchar = (char) b[i];
        outStr = outStr + tmpchar;
      }
    }
    return outStr;
  }

 /**
  * getDate
  * @author lcl
  * **/
  public static String getDate(String days, boolean fill) {
    Calendar rightNow = Calendar.getInstance();
    if (days != null && !days.equals("") && !days.equals("0")) {
      long time = rightNow.getTime().getTime() -
          Long.parseLong(days) * 24 * 60 * 60 * 1000;
      rightNow.setTimeInMillis(time);
    }
    int year = rightNow.get(Calendar.YEAR);
    int month = rightNow.get(Calendar.MONTH) + 1;
    int day = rightNow.get(Calendar.DATE);
    return year + "-" + ( (fill && month < 10) ? "0" : "") + month + "-" +
        ( (fill && day < 10) ? "0" : "") + day;
  }


  

  

  public static String GbToUtf8(String ret) throws UnsupportedEncodingException
  {
    String str=null;
    if(ret!=null)
      str=new String(ret.getBytes("GBK"),"utf-8");
    return str;
  }
  /**
       * getIP
       * @author lclַ
       * @return ip
       */
  public static String getIpAddr(Scan power) {
          String ip = power.getRequest().getHeader("x-forwarded-for");
          if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
              ip = power.getRequest().getHeader("Proxy-Client-IP");
          }
          if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
              ip = power.getRequest().getHeader("WL-Proxy-Client-IP");
          }
          if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
              ip = power.getRequest().getRemoteAddr();
          }
          return ip;
  }
  public static String cutHtmlCode(String str){
    if(str==null||str.equals(""))
      return "";
    else
      return str.replaceAll("<\\s*\\/*[a-zA-Z]+[^>]*[^\\x00-\\xff]*[^>]*>","");
  }
  public static String getPath(HttpServletRequest request){
	    return request.getContextPath();
  }
  
  public static String getDomain(HttpServletRequest request){
	    return request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
  }
  public static String getBasePath(HttpServletRequest request){
	  return getDomain(request)+getPath(request);
  }
  
  public static String getStringFromStrings(String[] strs,String spl){
	  StringBuffer sb = new StringBuffer();
	  for(int i=0;i<strs.length;i++){
		  sb.append(strs[i]).append(spl);
	  }
	  sb.deleteCharAt(sb.lastIndexOf(spl));
	  return sb.toString();
  }
  
  
  public static String fileSizeFormat(String lnFileSize)
  {
      double douReturnValue;
      String returnValue;
      String a;
      double lonGB;
      double lonMB;
      double lonKB;
      douReturnValue = 0.0D;
      double size = 0.0D;
      returnValue = "";
      a = "";
      lonGB = 1073741824D;
      lonMB = 1048576D;
      lonKB = 1024D;
      size = Double.parseDouble(lnFileSize);
      if(size >= lonGB)
      {
          douReturnValue = size / lonGB;
          a = "GB";
      } else
      if(size >= lonMB)
      {
          douReturnValue = size / lonMB;
          a = "MB";
      } else
      if(size >= lonKB)
      {
          douReturnValue = size / lonKB;
          a = "KB";
      } else
      {
          douReturnValue = size;
          a = "B&nbsp;";
      }
      returnValue = Double.toString(Math.round(douReturnValue))+a;

      return returnValue;
  }
  
  
  public static String cutString(String source,String spl,int index) throws Exception{
	  return source.substring(source.indexOf(spl, index)+1, source.length());
  }
  
  public static String cutBeginAndEndString(String source,String spl) throws Exception{

	  if(source.startsWith(spl)){
		  source = cutString(source,spl,0);
	  }
	  if(source.lastIndexOf(spl)+1==source.length()){
		  source = source.substring(0, source.length()-1);
	  }
	  return source;
  }
  public static String[] splitToArray(String oldStr, String token)
  {
      StringTokenizer oldToken = new StringTokenizer(oldStr, token);
      int len = oldToken.countTokens();
      String arr[] = new String[len];
      for(int i = 0; oldToken.hasMoreElements(); i++)
      {
          String newStr = oldToken.nextToken();
          arr[i] = newStr;
      }

      return arr;
  }
  
  public static String transferFileSeperator(String path, String type2)
  {
      type2 = type2.toLowerCase();
      if(type2.equals("local"))
          return Replace(path, "/", File.separator);
      if(type2.equals("http"))
          return Replace(path, File.separator, "/");
      else
          return path;
  }
  
  public static String Replace(String source, String oldString, String newString)
  {
      StringBuffer output = new StringBuffer();
      int lengthOfSource = source.length();
      int lengthOfOld = oldString.length();
      int posStart = 0;
      if(source.indexOf(oldString) == -1)
          return source;
      int pos;
      while((pos = source.indexOf(oldString, posStart)) >= 0) 
      {
          output.append(source.substring(posStart, pos));
          output.append(newString);
          posStart = pos + lengthOfOld;
      }
      if(posStart < lengthOfSource)
          output.append(source.substring(posStart));
      return output.toString();
  }
  /** 为以逗号分隔的字符串的每个单元加入引号,如:aa,bb-->'aa','bb' */
	public static String formatString(String src){
		StringBuffer result = new StringBuffer();
		result.append("");
		if (src!=null){
			String[] tmp = src.split(",");
			result.append("'"+tmp[0]+"'");
			for(int i=1;i<tmp.length;i++){
				result.append(",'"+tmp[i]+"'");
			}
		}		
		return result.toString();
	}	
	
  /** 截取指定字节数的字符串,且确保汉字不被拆分 */
	public static String cutString(String text, int textMaxChar){   
      int size,index;   
      String result = null;  
      if(textMaxChar<=0){   
      	result= text;   
      }else{   
          for(size=0,index=0;index<text.length()&&size<textMaxChar;index++){   
              size += text.substring(index,index+1).getBytes().length;   
          }   
          result = text.substring(0,index);   
      }  
      return result;   
  }
	
  /** 按yyyy-MM-dd格式格式化日期 */
	public static String formatDate(Date date){   
		if (date==null){
			return "";
		}else{
			return df.format(date);
		}
  }

}
